package com.ihr360.expr.core;

import com.ihr360.expr.ExprException;
import com.ihr360.expr.utils.Reflect;


/**
 * 二元运算抽象类
 */
public abstract class AbstractBinaryOperator extends ExprEvaluatable implements
        IBinaryOperator
{
    protected Expr lhs;
    protected Expr rhs;

    public AbstractBinaryOperator(ExprType type, Expr lhs, Expr rhs) {
        super(type);
        this.lhs = lhs;
        this.rhs = rhs;
    }

    public Expr getLHS() {
        return lhs;
    }

    public void setLHS(Expr lhs) {
        this.lhs = lhs;
    }

    public Expr getRHS() {
        return rhs;
    }

    public void setRHS(Expr rhs) {
        this.rhs = rhs;
    }

    @Override
    public void validate() throws ExprException {
        if (lhs == null){
            throw new ExprException("LHS of operator missing");
        }
        lhs.validate();
        if (rhs == null){
            throw new ExprException("RHS of operator missing");
        }
        rhs.validate();
    }
    @Override
    public int hashCode() {
        int hc = type.ordinal();
        if (lhs != null){
            hc ^= lhs.hashCode();
        }
        if (rhs != null){
            hc ^= rhs.hashCode();
        }
        return hc;
    }
    @Override
    public boolean equals(Object obj) {
        if (!obj.getClass().equals(getClass())){
            return false;
        }
        AbstractBinaryOperator b = (AbstractBinaryOperator) obj;
        return Reflect.equals(b.lhs, lhs) && Reflect.equals(b.rhs, rhs);
    }
}